import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { message, Spin, Tooltip } from 'antd';
import dayjs from 'dayjs';
import QuestionCircleFilled from '@ant-design/icons/QuestionCircleFilled';
import Modal from '@/components/Modal';
import ProForm, { type formConfigProps, type formListProps } from '@/components/ProForm';
import { recoveryInfo, dynamicTpl } from '@/api/modules/recovery';
import { validPhone } from '@/utils/validate';
import { deepFind } from '@/utils/util';
import OrderModal from './OrderModal';

import "./index.less";

const fieldNames = { label: 'name', value: 'id', groupLabel: 'name' };

const Comp = forwardRef((props: any, ref: any) => {
    const formRef = useRef(props);
    const orderRef: any = useRef();
    const [modalObj, setModalObj] = useState({
        width: '1200px',
        title: '录入回收单信息',
        open: false,
        loading: false,
        confirmLoading: false,
        id: undefined,
    });
    const [formConfig, setFormConfig] = useState<formConfigProps[]>([]);
    const [optionsMap, setOptionsMap] = useState({
        tagRes: {},
        transacionRes: {},
        channelRes: {},
        allGameRes: {},
        allUserRes: {},
    });

    const getDynaFormList = (group: any, server: any, preset_data?: any): formListProps[] => {
        const getValue = (obj: any) => {
            return `${obj.group_id}_${obj.attr_id}_${obj.attr_name}`;
        };
        return (group || []).reduce((iinit: any, iitem: any) => {
            const initialValue = preset_data ? getValue((preset_data.attrs || []).find((item: any) => Number(item.group_id) === Number(iitem.id))) : undefined;
            if (iitem.is_no_attr === 2) {
                iinit.push({
                    name: ['preset_data', `attr@${iitem.id}`],
                    label: iitem.group_name,
                    valueType: 'select',
                    options: iitem.attribute || [],
                    formProps: {
                        fieldNames: { ...fieldNames, value: 'option_id' },
                        mode: iitem.is_multiple === 1 ? 'multiple' : undefined,
                    },
                    required: true,
                    initialValue,
                });
            }
            if (iitem.is_no_attr === 1) {
                iinit.push({
                    name: ['preset_data', iitem.id],
                    label: iitem.group_name,
                    valueType: 'text',
                    required: true,
                    initialValue,
                });
            }
            return iinit;
        }, [{
            name: ['preset_data', 'server'],
            label: '游戏区服',
            valueType: 'cascader',
            options: server || [],
            formProps: { fieldNames },
            required: true,
            initialValue: preset_data ? [preset_data.game_area_id, preset_data.game_server_id] : undefined,
        }]);
    }
    const getFormConfig = (
        { tagRes, transacionRes, channelRes, allGameRes, allUserRes }: any,
        detail: any,
        dyncData: any,
    ):formConfigProps[] => {
        const { screenshot } = detail;
        const newRecovery_channel_id = detail.recovery_channel_id ? deepFind(channelRes.data, detail.recovery_channel_id) : undefined;
        const newTransaction_mode_id = detail.transaction_mode_id ? deepFind(transacionRes.data, detail.transaction_mode_id) : undefined;
        const newAccount_tag = (detail.account_tags || []).map((item: any) => item.id);
        const newGameimg_screenshot = ((screenshot || {}).gameimg || []).map((item: any) => ({
            status: 'done',
            url: item,
        }));
        const newPay_screenshot = ((screenshot || {}).pay || []).map((item: any) => ({
            status: 'done',
            url: item,
        }));
        const newOther_screenshot = ((screenshot || {}).other || []).map((item: any) => ({
            status: 'done',
            url: item,
        }));

        return [{
            span: 8,
            formList: [{
                name: 'game_id',
                label: '游戏名称',
                valueType: 'select',
                options: allGameRes.data,
                formProps: { fieldNames },
                onChange: getDynaTpl,
                required: true,
                initialValue: detail.game_id,
            }, {
                name: 'recovery_sn',
                label: '回收编号',
                valueType: 'text',
                hidden: true,
                initialValue: detail.recovery_sn,
            }, {
                name: 'recovery_channel_id',
                assistant: ['recovery_channel'],
                label: '回收渠道',
                valueType: 'cascader',
                options: channelRes.data,
                formProps: { fieldNames },
                required: true,
                initialValue: [newRecovery_channel_id, detail.recovery_channel],
                onChange: (...args: any) => {
                    formRef.current.setFieldsValue({
                        recovery_channel: (args[1] || []).map((item: any) => item.name).join('-'),
                    });
                },
            }, {
                name: 'recovery_time',
                label: '回收时间',
                valueType: 'datetime',
                required: true,
                initialValue: detail.recovery_time ? dayjs(detail.recovery_time) : undefined,
            }, {
                name: 'recovery_staff',
                assistant: ['recovery_staff_name'],
                label: '回收人员',
                valueType: 'user',
                required: true,
                initialValue: [detail.recovery_staff, detail.recovery_staff_name],
                options: allUserRes.data,
                formProps: { fieldNames: { label: 'nick_name', value: 'id', groupLabel: 'nick_name' } },
                onChange: (...args: any) => {
                    formRef.current.setFieldsValue({
                        recovery_staff_name: args[1].nick_name,
                    });  
                },
            }, {
                name: 'recovery_price',
                label: '回收成本',
                valueType: 'number',
                required: true,
                initialValue: detail.recovery_price,
            }, {
                name: 'sale_price',
                label: '销售价',
                valueType: 'number',
                required: true,
                initialValue: detail.sale_price,
            }, {
                name: 'account',
                label: '游戏账号',
                valueType: 'text',
                required: true,
                initialValue: detail.account,
            }, {
                name: 'password',
                label: '游戏密码',
                valueType: 'password',
                required: true,
                initialValue: detail.password,
            }, {
                name: 'pay_for',
                label: '是否包赔',
                valueType: 'radio',
                required: true,
                initialValue: detail.pay_for || 1,
                options: [{
                    label: '是',
                    value: 1,
                }, {
                    label: '否',
                    value: 2
                }],
            }, {
                name: 'pay_type',
                label: '支付方式',
                valueType: 'select',
                required: true,
                initialValue: detail.pay_type,
                options: [{
                    label: '个人支付',
                    value: '个人支付',
                }, {
                    label: '公司支付',
                    value: '公司支付',
                }],
            }, {
                name: 'recovery_no',
                label: '第三方单号',
                valueType: 'text',
                initialValue: detail.recovery_no,
            }, {
                name: 'account_tag',
                assistant: ['account_tags'],
                label: '账号标签',
                valueType: 'select',
                initialValue: [newAccount_tag, detail.account_tags],
                options: tagRes.data,
                formProps: { fieldNames, mode: 'multiple', maxTagCount: 'responsive' },
                onChange: (...args: any) => {
                    formRef.current.setFieldsValue({
                        account_tags: (args[1] || []).map((item: any) => ({
                            name: item.name,
                            id: item.id,
                        })),
                    })
                }
            }],
        }, {
            span: 8,
            formList: [{
                name: 'transaction_mode_id',
                assistant: ['transaction_mode'],
                label: '交易方式',
                valueType: 'cascader',
                options: transacionRes.data,
                formProps: { fieldNames },
                initialValue: [newTransaction_mode_id, detail.transaction_mode],
                required: true,
                onChange: (...args: any) => {
                    formRef.current.setFieldsValue({
                        transaction_mode: (args[1] || []).map((item: any) => item.name).join('-'),
                    })
                },
            }, {
                name: 'mobile',
                label: '绑定手机',
                assistant: ['number_order_id'],
                valueType: 'search',
                required: true,
                initialValue: [detail.mobile, detail.number_order_id],
                formProps: {
                    enterButton: '关联订单',
                    onSearch: (value: any) => {
                        if (!validPhone(value)) return message.warning('请输入正确的手机号');
                        orderRef.current.show({ mobile: value });
                    },
                }
            }, {
                name: 'freeze_day',
                label: <>冻结天数<Tooltip title="设置冻结天数，冻结天数到期时才上架到商品列表"><QuestionCircleFilled /></Tooltip></>,
                valueType: 'text',
                required: true,
                initialValue: detail.freeze_day || 0,
                hidden: !modalObj.id,
            }, {
                name: 'bind_id',
                label: '绑定人员',
                assistant: ['bind_id_name'],
                valueType: 'user',
                initialValue: [detail.bind_id, detail.bind_id_name],
                options: allUserRes.data,
                formProps: { fieldNames: { label: 'nick_name', value: 'id', groupLabel: 'nick_name' } },
                onChange: (...args: any) => {
                    formRef.current.setFieldsValue({
                        bind_id_name: args[1].nick_name,
                    });  
                },
            }, {
                name: 'remarks',
                label: '',
                valueType: 'textarea',
                formProps: { rows: 6 },
                initialValue: detail.remarks,
                placeholder: '换绑信息邮箱绑定手机、邮箱密码、设备码、二级密码、支付密码、支付密码、手势密码等',
            }, {
                name: 'after_sales_remarks',
                label: '',
                valueType: 'textarea',
                formProps: { rows: 6 },
                initialValue: detail.after_sales_remarks,
                placeholder: '客户来源、合同编号、包赔编号等',
            }, {
                name: 'account_feature',
                label: '',
                valueType: 'textarea',
                formProps: { rows: 6 },
                initialValue: detail.account_feature,
                placeholder: '账号亮点',
            }]
        }, {
            span: 8,
            formList: dyncData ? getDynaFormList(dyncData.group, dyncData.server, detail.preset_data) : [],
        }, {
            span: 24,
            formList: [{
                name: 'gameimg_screenshot',
                label: '游戏截图',
                defaultValue: newGameimg_screenshot,
                valueType: 'upload',
            }, {
                name: 'pay_screenshot',
                label: <>上传支付截图<Tooltip title="上传微信支付截图，支付宝支付截图，其他交易app支付截图"><QuestionCircleFilled /></Tooltip></>,
                defaultValue: newPay_screenshot,
                valueType: 'upload',
            }, {
                name: 'other_screenshot',
                label: <>上传其他截图<Tooltip title="上传游戏交易平台订单截图，交易成功截图。"><QuestionCircleFilled /></Tooltip></>,
                defaultValue: newOther_screenshot,
                valueType: 'upload',
            }]
        }];
    }
    const onCancel = () => {
        setModalObj((pre) => ({ ...pre, open: false }));
    };
    const onOk = () => {
        formRef.current.validateFields().then(async (values: any) => {
            const {
                gameimg_screenshot, other_screenshot, pay_screenshot, // 图片只要url
                recovery_channel_id, transaction_mode_id, // 取最后一级id
                recovery_time, // 日期格式
                preset_data: { server, ...otherPreset }, // 动态表单数据重新组装
                ...other
            }: any = values;
            const postData = {
                ...other,
                account_tag: undefined,
                recovery_time: recovery_time.format('YYYY-MM-DD HH:mm:ss'),
                recovery_channel_id: (recovery_channel_id || []).pop(),
                transaction_mode_id: (transaction_mode_id || []).pop(),
                gameimg_screenshot: (gameimg_screenshot || []).map((item: any) => item.url),
                other_screenshot: (other_screenshot || []).map((item: any) => item.url),
                pay_screenshot: (pay_screenshot || []).map((item: any) => item.url),
                preset_data: {
                    // 全部必填强校验可以直接放心取值
                    game_server_id: server[1],
                    game_area_id: server[0], // server区服 必填强校验可以直接取值
                    attrs: Object.values(otherPreset).reduce((init: any, item: any) => ([ ...init, ...(Array.isArray(item) ? item : [item]) ]), []),
                },
            };
            console.log(postData);
            try {
                setModalObj((pre) => ({ ...pre, loading: true, confirmLoading: true }));
                // const { data } = await addRecovery(values);
                setModalObj((pre) => ({ ...pre, loading: false, confirmLoading: false }));
            } catch (err) {
                setModalObj((pre) => ({ ...pre, loading: false, confirmLoading: false }));
            }
        })
    };
    const getDynaTpl = async (game_id: number) => {
        try {
            const { data } = await dynamicTpl({ game_id });
            const { group, server }: any = data || {};
            setFormConfig((pre: any) => {
                return pre.reduce((init: any, item: any, index: any) => {
                    if (index === 2) {
                        // 相当于第三列 在第三列添加动态的表单
                        init.push({ ...item, formList: getDynaFormList(group, server) });
                    } else {
                        init.push(item);
                    }
                    return init;
                }, []);
            });
        } catch (err) {
            console.log(err, '获取动态表单模板失败!');
        }
    };
    const initData = async () => {
        try {
            let dyncData;
            const asyncArr = [];
            if (modalObj.id) asyncArr.push(recoveryInfo({ id: modalObj.id  }));
            setModalObj((pre) => ({ ...pre, loading: true, confirmLoading: true }));
            const [infoRes]: any = await Promise.all(asyncArr);
            if (modalObj.id) {
                const { data } = await dynamicTpl({ game_id: infoRes.data.game_id });
                dyncData = data || {};
            }
            const newDetail = (infoRes && infoRes.data) || {};
            setFormConfig(getFormConfig({ ...optionsMap }, newDetail, dyncData));
            setModalObj((pre) => ({
                ...pre,
                loading: false,
                confirmLoading: false,
                defail: newDetail,
            }));
        } catch (err) {
            console.log(err, '报错都会走这里！');
            setModalObj((pre) => ({ ...pre, loading: false, confirmLoading: false }));
        }
    };
    useImperativeHandle(ref, () => ({
        modalObj,
        show: () => setModalObj((pre) => ({ ...pre, open: true, id: undefined, detail: undefined })),
        showDetail: (id: any) => setModalObj((pre) => ({ ...pre, open: true, id })),
        setOptionsMap,
    }));

    useEffect(() => {
        if (modalObj.open === true) initData();
    }, [modalObj.open]);

	return (
        <>
            {
                modalObj.open ? (
                    <>
                        <Modal
                            {...modalObj}
                            onOk={onOk}
                            onCancel={onCancel}
                            loading={false}
                        >
                            {
                                modalObj.loading ? <Spin spinning /> : <ProForm ref={formRef} formConfig={formConfig} />
                            }
                        </Modal>
                        <OrderModal ref={orderRef} />
                    </>
                ) : ''
            }
        </>
	);
});

Comp.displayName = 'recovery-form-modal';

export default Comp;
